<template>
  <el-tooltip v-if="trDisabled" :visible="!props.applyIsDisabled" class="box-item"
              content="请先点击（处方新增）按钮后，再添加药品"
              effect="dark" placement="right">
    <el-button :disabled="!props.applyIsDisabled" plain type="primary" @click="handleAddDrug">
      <template #icon>
        <i-ep-plus/>
      </template>
      添加药品
    </el-button>
  </el-tooltip>
  <el-button v-if="trDisabled" :disabled="!props.applyIsDisabled" plain type="danger" @click="emptyDrugList(true)">
    <template #icon>
      <i-ep-delete-filled/>
    </template>
    清空
  </el-button>
  <el-form ref="formRef" :model="form" :rules="rules">
    <el-table ref="prescriptionItemRef" :border="true" :data="form.prescriptionItemList"
              :header-cell-style="$headerCellStyle" :stripe="true"
              height="400px" highlight-current-row @select-all="selectAll">
      <el-table-column :align="'center'" fixed="left" type="selection" width="55">
        <template #default="scope">
          <el-checkbox v-model="scope.row.checkOk" @change="checkboxChange($event, scope.row)"/>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" fixed="left" label="申请单组号" prop="itemIdenticalGroup" width="90">
        <template #default="scope">
          <el-form-item :prop="'prescriptionItemList.' + scope.$index + '.itemIdenticalGroup'"
                        :rules="rules.itemIdenticalGroup" class="table-form-margin">
            <el-input v-model="scope.row.itemIdenticalGroup"
                      v-keyupEnter="{ index: scope.$index, name: 'itemIdenticalGroup' }" class="groupNumber"
                      clearable @blur="sortByItemIdenticalGroup"
                      type="number"></el-input>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" fixed="left" label="处方属性" prop="prescAttr" width="120px">
        <template #default="scope">
          <el-form-item :prop="'prescriptionItemList.' + scope.$index + '.prescAttr'"
                        :rules="rules.prescAttr">
            <el-select v-model="scope.row.prescAttr" class="width-120" clearable placeholder="请选择处方属性"
                       @change="prescAttrChange(scope.$index, scope.row)">
              <el-option v-for="dict in dictDataMap['prescription_type']" :key="dict.dictValue"
                         :label="dict.dictLabel" :value="dict.dictValue"/>
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" fixed="left" label="诊断" width="180">
        <template #default="scope">
          <el-form-item :prop="'prescriptionItemList.' + scope.$index + '.icdCode'" :rules="rules.icdCode">
            <diagnosis-select v-model="scope.row.icdCode"
                              @option-change="optionChange($event, scope.$index,scope.row)"/>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" fixed="left" label="组号" prop="groupNumber" width="80">
        <template #default="scope">
          <el-form-item v-if="trDisabled" :prop="'prescriptionItemList.' + scope.$index + '.groupNumber'"
                        :rules="rules.groupNumber" class="table-form-margin">
            <el-input v-model="scope.row.groupNumber" clearable type="number"
                      @blur="groupNumberBlur(scope.$index, scope.row)"></el-input>
          </el-form-item>
          <span v-else>{{ scope.row.groupNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" fixed="left" label="药品" prop="drugName" width="300">
        <template #default="scope">
          <el-form-item v-if="trDisabled" :prop="'prescriptionItemList.' + scope.$index + '.drugName'"
                        :rules="rules.drugName" class="table-form-margin">
            <automatic-completion :ref="(el:any) => setItemAutomaticRef(el, scope.$index)" :dict-array="dictArray"
                                  :table-body-list="tableBodyList"
                                  :table-head-list="tableHeadList" :title="itemTitle"
                                  :right-div-show-type="'westernMedicine'" :width="978"
                                  style="width: 100%;" @itemNameInput="itemNameInput($event, scope.$index, scope.row)"
                                  @rowClick="rowClick($event, scope.$index, scope.row)"/>
          </el-form-item>
          <span v-else>{{ scope.row.groupNumberStyle }} {{ scope.row.drugName }}</span>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="途径" prop="channel" width="130">
        <template #default="scope">
          <el-form-item v-if="trDisabled" :prop="'prescriptionItemList.' + scope.$index + '.channel'"
                        :rules="rules.channel" class="table-form-margin">
            <administration-index :disabled="scope.row.channelDisabled"
                                  :placeholder="'请选择途径'" :value="scope.row.channel"
                                  style="width: 100%"
                                  @administrationInfoChange="administrationInfoChange($event, scope.$index, scope.row)"/>
          </el-form-item>
          <span v-else>{{ scope.row.channelName }}</span>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="单次用量" prop="singleDosage" width="120">
        <template #default="scope">
          <el-form-item v-if="trDisabled" :prop="'prescriptionItemList.' + scope.$index + '.singleDosage'"
                        :rules="rules.singleDosage" class="table-form-margin">
            <el-input v-model="scope.row.singleDosage" class="input-mr" clearable
                      @blur="inputBlur(scope.$index)">
              <template #append>{{ scope.row.singleUnitName }}</template>
            </el-input>
          </el-form-item>
          <span v-else style="margin-left: -15px"> {{ scope.row.singleDosage }}<dict-data-tag
            :options="dictDataMap['dose_unit']" :value="scope.row.singleUnit"
            style="margin: -23px -20px 0px 35px"/></span>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="频次" prop="performFreq" width="130">
        <template #default="scope">
          <el-form-item v-if="trDisabled" :prop="'prescriptionItemList.' + scope.$index + '.performFreq'"
                        :rules="rules.performFreq" class="table-form-margin">
            <perform-index ref="performIndex" :disabled="scope.row.performFreqDisabled" :placeholder="'请选择频次'"
                           :value="scope.row.performFreq" style="width: 100%"
                           @performFreqInfoChange="performFreqInfoChange($event, scope.$index)"/>
          </el-form-item>
          <span v-else>{{ scope.row.performFreqName }}</span>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="天数" prop="abidance" width="100">
        <template #default="scope">
          <el-form-item v-if="trDisabled" :prop="'prescriptionItemList.' + scope.$index + '.abidance'"
                        :rules="rules.abidance" class="table-form-margin">
            <el-input v-model="scope.row.abidance" class="input-mr" clearable
                      @blur="inputBlur(scope.$index)"></el-input>
          </el-form-item>
          <span v-else>{{ scope.row.abidance }}</span>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="数量" prop="num" width="110">
        <template #default="scope">
          <el-form-item v-if="trDisabled" :prop="'prescriptionItemList.' + scope.$index + '.num'"
                        :rules="rules.num" class="table-form-margin">
            <el-input v-model="scope.row.num" class="input-mr" clearable @blur="numInputBlur(scope.$index)">
              <template #append>{{ scope.row.unitName }}</template>
            </el-input>
          </el-form-item>
          <span v-else>{{ scope.row.num }} <dict-data-tag :options="dictDataMap['spec_unit']"
                                                          :value="scope.row.unit"
                                                          style="margin: -23px -20px 0px 27px"/></span>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="免皮试" prop="noSkin" width="70px">
        <template #default="scope">
          <el-form-item v-if="trDisabled" class="table-form-margin noSkin-checkbox">
            <el-checkbox v-model="scope.row.noSkin"></el-checkbox>
          </el-form-item>
          <span v-else>
                        <dict-data-tag :options="dictDataMap['sys_yes_no']" :value="scope.row.noSkin"/>
                    </span>
        </template>
      </el-table-column>
      <!--      <el-table-column :align="'center'" label="单价" prop="price" width="75">-->
      <!--        <template #default="scope">-->
      <!--          {{ parseFloat(scope.row.price).toFixed(2) }}元-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column :align="'center'" label="总价" prop="sumPrice" width="90">-->
      <!--        <template #default="scope">-->
      <!--          {{ parseFloat(scope.row.sumPrice).toFixed(2) }}元-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column :align="'center'" label="滴速" prop="dripSpeed" width="110px">
        <template #default="scope">
          <el-form-item v-if="trDisabled">
            <el-select v-model="scope.row.dripSpeed" class="width-120" clearable placeholder="请选择滴速"
                       @change="dripSpeedChange($event, scope.$index, scope.row)">
              <el-option v-for="dict in dictDataMap['sys_drop_speed']" :key="dict.dictValue"
                         :label="dict.dictLabel" :value="dict.dictValue"/>
            </el-select>
          </el-form-item>
          <span v-else><dict-data-tag :options="dictDataMap['sys_drop_speed']"
                                      :value="scope.row.dripSpeed"/></span>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="规格" prop="packageSpec"/>
      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="厂商" prop="firmName">
        <template #default="scope">
          <div>{{ scope.row.firmName }}</div>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="医生说明" width="94px">
        <template #default="scope">
          <el-form-item v-if="trDisabled" class="table-form-margin">
            <el-input v-model="scope.row.remarks" class="input-mr" clearable></el-input>
          </el-form-item>
          <span v-else>{{ scope.row.remarks }}</span>
        </template>
      </el-table-column>

      <el-table-column v-if="trDisabled" :align="'center'" class-name="small-padding fixed-width" fixed="right"
                       label="操作" width="65">
        <template #default="scope">
          <el-tooltip class="item" content="删除" effect="dark" placement="top">
            <el-button circle type="danger" @click="handleDelete(scope.$index, scope.row)">
              <template #icon>
                <i-ep-delete/>
              </template>
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
  </el-form>
</template>

<script lang="ts" setup>
import {autoPrescriptionList} from "@/api/drug/drugStock.ts"
import {useDictStoreHook} from "@/store/modules/dict";
import {jsonStrInObj, prescriptionList} from "@/utils/autoComplete"
import {positiveNumberNotNull} from "@/utils/myRules.ts";
import {listHisDiagnosis} from "@/api/diagnosis/hisDiagnosis.ts";

const dictStore = useDictStoreHook();
let dictDataMap = ref(dictStore.isTypeGetData('spec_unit', 'sys_yes_no', 'dose_unit', 'sys_drop_speed', 'prescription_type'))
// 创建一个ref数组来存储每个automatic-completion实例
const itemAutomaticRefs = ref<any[]>([]);

// 在模板中使用动态ref
function setItemAutomaticRef(el, index) {
  if (el) {
    itemAutomaticRefs.value[index] = el;
  }
}

const prescriptionItemRef = ref()
const {proxy} = getCurrentInstance() as any;
const emits = defineEmits(["itemSubmitOk", "submitOk", "quoteOk"])
const trDisabled = ref<boolean>(false)
// 诊断列表
const hisDiagnosisList = ref<any>([])
// 勾选的明细对象数组
const detailInfoList = ref<any>([]);
const ids = ref([]);
// 跨组件给子组件传值
provide('getHisDiagnosisList', hisDiagnosisList);

const props = defineProps({
  orgId: {
    type: String,
    default: ""
  },
  applyIsDisabled: {
    type: Boolean,
    default: true
  },
});
const formRef = ref()
// 表单参数
const form = ref<any>({
  // 药品价格list
  prescriptionItemList: []
})
const autoForm = ref<any>({
  drugClassArray: "",
  storageId: "",
  itemInfo: "",
  orgId: props.orgId
})
// 项目选择自动补全窗体名称
const itemTitle = ref('选择项目')
// 项目选择自动补全表格表头
const tableHeadList = ref(jsonStrInObj(prescriptionList))
// 项目选择自动补全表格数据
const tableBodyList = ref([])
// 项目选择自动补全字典数组
const dictArray = ref(['bill_item_class_dict', 'is_medical_insurance'])

// 表单校验
const rules = ref({
  groupNumber: [
    {required: true, validator: positiveNumberNotNull, trigger: "blur"}
  ],
  abidance: [
    {required: true, validator: positiveNumberNotNull, trigger: "blur"}
  ],
  itemIdenticalGroup: [
    {required: true, validator: positiveNumberNotNull, trigger: "blur"}
  ],
  num: [
    {required: true, validator: positiveNumberNotNull, trigger: "blur"}
  ],
  singleDosage: [
    {required: true, message: "单次用量不能为空", trigger: "change"}
  ],
  drugName: [
    {required: true, message: "药品不能为空", trigger: "blur"}
  ],
  channel: [
    {required: true, message: "用药途径不能为空", trigger: "change"}
  ],
  performFreq: [
    {required: true, message: "执行频次不能为空", trigger: "change"}
  ],
  prescAttr: [
    {required: true, message: "处方属性不能为空", trigger: "change"}
  ],
  icdCode: [
    {required: true, message: "诊断不能为空", trigger: "change"}
  ],
})


/** 查询患者诊断表列表 */
function getDiagnosisList() {
  const form = {
    patientId: proxy.$patientId,
    clinicId: proxy.$clinicId
  }
  listHisDiagnosis(form).then((response: any) => {
    hisDiagnosisList.value = response.data;
  });
}


// 行选中 默认按照组号相同的勾选或者取消勾选
function checkboxChange(e: boolean, detail: any) {
  if (e) {
    form.value.prescriptionItemList.forEach((prescriptionItem: any) => {
      if (prescriptionItem.itemIdenticalGroup === detail.itemIdenticalGroup) {
        prescriptionItem.checkOk = true
      }
    })
  } else {
    form.value.prescriptionItemList.forEach((prescriptionItem: any) => {
      if (prescriptionItem.itemIdenticalGroup === detail.itemIdenticalGroup) {
        prescriptionItem.checkOk = false
      }
    })
  }

}

// 全选/反选
function selectAll() {
  if (ids.value.length === form.value.prescriptionItemList.length) {
    form.value.prescriptionItemList.forEach((prescriptionItem: any) => {
      prescriptionItem.checkOk = false
    })
    ids.value = []
  } else {
    form.value.prescriptionItemList.forEach((prescriptionItem: any) => {
      prescriptionItem.checkOk = true
    })
    ids.value = form.value.prescriptionItemList.map(item => item.detailId);
  }

}

/**
 * 打开西药明细事件
 * @param drugClassArrayParam
 * @param storageId
 */
function setDrugClassArray(drugClassArrayParam: any, storageId: string) {
  autoForm.value.drugClassArray = drugClassArrayParam
  autoForm.value.storageId = storageId
  trDisabled.value = true
}

/**
 * 途径点击事件
 */
function administrationInfoChange(e, index: number, _row: any) {
  const dict = toRaw(e)
  form.value.prescriptionItemList[index].channel = dict.dictValue
  // 途径为 皮试的话，将免皮试设置为不选中
  form.value.prescriptionItemList[index].noSkin = dict.dictValue !== "112";


}

/**
 * 频次点击事件
 */
function performFreqInfoChange(e: any, index: number) {
  const performFreqInfo = toRaw(e)
  form.value.prescriptionItemList[index].performFreq = performFreqInfo.freqId
  form.value.prescriptionItemList[index].performFreqInfo = performFreqInfo
  calculatedQuantityAndMoney(index)
}

/**
 * 计算数量 和金额
 */
function calculatedQuantityAndMoney(index: number) {
  // 最小剂量
  const singleDosageMin = form.value.prescriptionItemList[index].singleDosageMin
  // 实际开出剂量
  const singleDosage = form.value.prescriptionItemList[index].singleDosage
  // 包装数量
  const packageNum = form.value.prescriptionItemList[index].packageNum
  if (typeof singleDosageMin !== "undefined" && typeof singleDosage !== "undefined" && typeof packageNum !== "undefined") {
    // 天数
    const abidance = form.value.prescriptionItemList[index].abidance
    // 获取频次对应的服用次数
    const performTime = form.value.prescriptionItemList[index].performFreqInfo.performTime ?
      form.value.prescriptionItemList[index].performFreqInfo.performTime.split("-").length : 1
    // 计算实际开出的单次用量和最小剂量的商
    const num: number = Number(Math.ceil(singleDosage / singleDosageMin))
    const amount: number = Number(Math.ceil(performTime * num * abidance))
    // 列表中总数量
    let sumAmount: number = 1;
    // if (amount % packageNum > 1) {
    sumAmount = Number(Math.ceil(amount / packageNum))
    // }
    // 给总数量赋值
    form.value.prescriptionItemList[index].num = sumAmount
    // 给总价赋值
    form.value.prescriptionItemList[index].sumPrice = Number((sumAmount * form.value.prescriptionItemList[index].price).toFixed(2))
  }
}

/**
 * 单次剂量input失去焦点事件
 */
function inputBlur(index: number) {
  calculatedQuantityAndMoney(index)
}

/**
 * 直接修改数量事件
 * @param index
 */
function numInputBlur(index: number) {
  // 给总价赋值
  form.value.prescriptionItemList[index].sumPrice = Number(form.value.prescriptionItemList[index].num * form.value.prescriptionItemList[index].price).toFixed(2)
}

/**
 * 滴速点击事件
 */
function dripSpeedChange(e, _index: number, row: any) {
  const sysDropSpeedArr: any = toRaw(dictDataMap.value['sys_drop_speed'])
  const indexNum = sysDropSpeedArr.findIndex((sysDropSpeed: any) => {
    return sysDropSpeed.dictValue === e
  })
  if (indexNum > -1) {
    if (row.remarks) {
      row.remarks = row.remarks + "," + sysDropSpeedArr[indexNum].dictLabel;
    } else {
      row.remarks = sysDropSpeedArr[indexNum].dictLabel
    }
  }
}

/** 自动补全后台查询 */
function getListDrugItem(index: number) {
  if (autoForm.value.itemInfo) {
    autoForm.value.orgId = props.orgId
    autoPrescriptionList(autoForm.value).then(res => {
      // 打开自动补全弹出框
      itemAutomaticRefs.value[index].init()
      tableBodyList.value = res.data

    })
  } else {
    tableBodyList.value = []
  }
}

/**
 * 添加药品
 */
function handleAddDrug() {
  (formRef.value as any).validate(valid => {
    if (valid) {
      if (form.value.prescriptionItemList.length > 0 &&
        form.value.prescriptionItemList[form.value.prescriptionItemList.length - 1].abidance > 7
        && !form.value.prescriptionItemList[form.value.prescriptionItemList.length - 1].remarks
      ) {
        return ElMessageBox.prompt(`${form.value.prescriptionItemList[form.value.prescriptionItemList.length - 1].drugName}
          药品用量大于7天，请填写超量说明`, '超量说明', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^[\s\S]+$/,
          inputErrorMessage: '超量说明不能为空',
        })
          .then(({value}) => {
            form.value.prescriptionItemList[form.value.prescriptionItemList.length - 1].remarks = value
            handleAddDrug()
          })
          .catch(() => {
            ElMessage.error("取消输入")
          })
      }
      if (form.value.prescriptionItemList.length >= 5) {
        return ElMessage.error("根据《处方管理办法》规定，为了规范用药，减少多药联用可能带来的不良反应，" +
          "每张处方不得超过 5 种药品，如需开药，请开具新处方。");
      }
      // 最大的组号
      let maxGroupNumber = 0
      if (form.value.prescriptionItemList.length > 0) {
        // 获取表格内最大的组号
        maxGroupNumber = Math.max.apply(Math, form.value.prescriptionItemList.map((item: any) => {
          return item.groupNumber
        }))
      }
      form.value.prescriptionItemList.push({
        // 是否免皮试 保存、修改时需要单独处理 true-> Y , false-> N
        noSkin: true,
        sumPrice: 0.00,
        price: 0.00,
        groupNumber: maxGroupNumber + 1,
        drugName: "",
        abidance: 1,
        num: 1,
        isShow: true,
        checkOk: true,
        // 途径是否禁用
        channelDisabled: false,
        // 频次是否禁用
        performFreqDisabled: false
      })
    }
  })
}

/**
 * 删除药品明细
 */
function handleDelete(index: number, _row: any) {
  ElMessageBox.confirm('删除后数据将会丢失，确定要继续操作吗？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    form.value.prescriptionItemList.splice(Number(index), 1)
  }).catch(() => {
    ElMessage.info("操作终止")
  })
}

/**
 * 明细行数据校验
 */
function itemValidate() {
  (formRef.value as any).validate(valid => {
    if (valid) {
      emits("itemSubmitOk", form.value)
    }
  })
}

// 清空药品列表
function emptyDrugList(type: boolean) {
  if (type) {
    ElMessageBox.confirm('重置后未保存的数据将会丢失，确定要继续操作吗？',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => {
      emptyPrescriptionItemList()
    }).catch(() => {
      ElMessage.info("操作终止")
    })
  } else {
    emptyPrescriptionItemList()
  }
}

/** 项目名称自动补全检索 */
function itemNameInput(e: any, index: number, _row: any) {
  autoForm.value.itemInfo = e
  getListDrugItem(index)
}

/** 主表行点击事件 */
function applyRowClick(row: any) {
  const rows = toRaw(row)
  emptyPrescriptionItemList()
  setItemFromTemplate(rows)
}


/** 项目列表行点击事件 */
function rowClick(e: any, index: number, row: any) {
  itemAutomaticRefs.value[index].setItemName(e.drugName)
  itemAutomaticRefs.value[index].closePopover()
  row.isShow = true
  row.sumPrice = 0.00
  row.singleDosageMin = e.dose
  row.singleDosage = e.dose
  row.singleUnitName = e.doseUnitsName
  row.singleUnit = e.doseUnits
  row.unitName = e.unitsName
  row.minUnits = e.minUnits
  row.packageUnits = e.packageUnits
  row.packageSpec = e.packageSpec
  row.minSpec = e.minSpec
  row.packSize = e.packSize
  row.firmName = e.firmName
  row.firmId = e.firmId
  row.drugName = e.drugName
  row.drugCode = e.drugCode
  row.price = e.price
  row.abidance = 1
  row.sumPrice = e.price * 1
  row.batchNo = e.batchNo
  row.packageNum = e.packageNum
  row.packageNumCalculate = e.packSize === "1" ? 1 : e.packageNum
  row.identicalInfoId = e.identicalInfoId
  row.tradePrice = e.tradePrice
  row.priceId = e.drugPriceId
  if (!row.channel) {
    row.channel = e.channel
  }
  if (!row.performFreq) {
    row.performFreq = e.performFreq
    row.performFreqInfo = dictStore.getAppointPerformFreqInfo(e.performFreq)
  }
  row.drugInfoId = e.drugInfoId
  row.sort = index + 1
  inputBlur(index)
  tableBodyList.value = []
}

// 组号input焦点消失事件
function groupNumberBlur(index: number, row: any) {
  // 获取list所有行
  const rows = form.value.prescriptionItemList
  // 当前行行号
  const groupNumber = Number(row.groupNumber)
  // 当前行的前一行
  const previousRow = rows[index - 1]
  const previousRowGroupNumber = previousRow.groupNumber;
  if (previousRowGroupNumber === groupNumber) {
    row.channel = previousRow.channel
    row.performFreq = previousRow.performFreq
    performFreqInfoChange(dictStore.getAppointPerformFreqInfo(previousRow.performFreq), index)
    row.channelDisabled = true
    row.performFreqDisabled = true
  } else {
    row.channelDisabled = false
    row.performFreqDisabled = false
  }
  const groupNumberIndex = form.value.prescriptionItemList.findIndex((item: any) => {
    return groupNumber === item.groupNumber
  })
  if (groupNumberIndex > -1 && groupNumber !== previousRowGroupNumber) {
    ElMessage.error("相同的组号不能相邻，请重新输入")
  }
}

/**
 * 处方属性点击事件
 * @param _index
 * @param row
 */
function prescAttrChange(_index: number, row: any) {
  const currentItemIdenticalGroup = row.itemIdenticalGroup;
  const currentPrescAttr = row.prescAttr;

  // 遍历处方项列表
  form.value.prescriptionItemList.forEach((item: any) => {
    if (item.itemIdenticalGroup === currentItemIdenticalGroup) {
      // 将相同 itemIdenticalGroup 的 prescAttr 设置为当前行的 prescAttr 值
      item.prescAttr = currentPrescAttr;
    }
  });
}


/********************* 在处方模板菜单中调用 模板菜单中：处方模板主记录点击调用事件  **********************/
function templateMene() {
  trDisabled.value = true
}

function trDisabledInFalse() {
  trDisabled.value = false
}

// 从模板给编辑列表赋值
function setItemFromTemplate(rows: any) {
  emptyPrescriptionItemList()
  // 获取模板明细list
  const detailList = rows.detailList
  detailList.forEach((detail: any, index: number) => {
    detail.itemId = ""
    detail.isShow = true
    detail.drugName = detail.itemName
    detail.itemClass = detail.showItemClass
    detail.packageNumCalculate = detail.packSize === "1" ? 1 : detail.packageNum
    // 设置免皮试 如果是不能编辑状态 noSkin 设置为 true或者false，用于多选按钮选中，否则设置为 Y或者N，用于字典显示
    // detail.noSkin = trDisabled.value === true ? detail.noSkin === "Y" : detail.noSkin
    detail.singleUnitName = dictStore.getMateDictInfo(dictDataMap.value['dose_unit'], detail.singleUnit).dictLabel
    const unit = detail.packSize === "1" ? detail.minUnits : detail.packageUnits
    detail.unitName = dictStore.getMateDictInfo(dictDataMap.value['spec_unit'], unit).dictLabel
    // 设置免皮试 如果是不能编辑状态 noSkin 设置为 true或者false，用于多选按钮选中，否则设置为 Y或者N，用于字典显示
    detail.noSkin = detail.noSkin === "Y"
    detail.unit = unit
    detail.checkOk = true
    form.value.prescriptionItemList.push(detail)
    // 自动补全组件赋值
    nextTick(() => {
      if (itemAutomaticRefs.value[index]) {
        itemAutomaticRefs.value[index].setItemName(detail.drugName)
      }
    })
  })
  // nextTick(() => {
  //   prescriptionItemRef.value.toggleAllSelection();
  // })
}

// 模板引用
function quoteRules() {
  form.value.prescriptionItemList = form.value.prescriptionItemList.filter((item: any) => item.checkOk);
  (formRef.value as any).validate(valid => {
    if (valid) {
      if (form.value.prescriptionItemList.length > 0) {
        emits("quoteOk", form.value.prescriptionItemList)
      } else {
        detailInfoList.value = []
        emits("quoteOk", form.value.prescriptionItemList)
      }
    }
  })
}

// 按 itemIdenticalGroup 排序
function sortByItemIdenticalGroup() {
  form.value.prescriptionItemList.sort((a, b) => {
    if (a.itemIdenticalGroup < b.itemIdenticalGroup) {
      return -1;
    }
    if (a.itemIdenticalGroup > b.itemIdenticalGroup) {
      return 1;
    }
    return 0;
  });
}

// 清空列表
function emptyPrescriptionItemList() {
  form.value.prescriptionItemList = []
}

/**
 * 诊断选择事件
 * @param e
 * @param index
 * @param row
 */
function optionChange(e, index, row) {
  row.diagnosisList = e
  row.icdCode = e.icdCode
  row.icdName = e.icdName
  const currentItemIdenticalGroup = row.itemIdenticalGroup;
  const currentIcdCode = row.icdCode;

  // 遍历处方项列表
  form.value.prescriptionItemList.forEach((item: any) => {
    if (item.itemIdenticalGroup === currentItemIdenticalGroup) {
      // 将相同 itemIdenticalGroup 的 icdCode 设置为当前行的 icdCode 值
      item.icdCode = currentIcdCode;
    }
  });
}

defineExpose({
  emptyDrugList,
  setDrugClassArray,
  handleAddDrug,
  itemValidate,
  applyRowClick,
  templateMene,
  trDisabledInFalse,
  quoteRules,
  emptyPrescriptionItemList
})

getDiagnosisList()
</script>

<style scoped>
:deep(.el-input-group__append) {
  padding: 0 5px;
  width: 40px;
}

:deep(.el-input__wrapper .el-input__inner) {
  margin-right: -15px;
}

:deep(.el-form-item__content) {
  margin-bottom: 6px;
}

:deep(.el-form-item__error) {
  font-size: 11px;
  color: #ff0000;
}

.noSkin-checkbox {
  margin-left: 15px;
}
</style>
